package com.ricardoteix.subtitle.parsers {
	import com.ricardoteix.subtitle.events.FileParserEvent;
	import com.ricardoteix.subtitle.SubtitleBlock;
	import com.ricardoteix.subtitle.SubtitleTime;
	import com.ricardoteix.subtitle.SubtitleType;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Ricardo Teixeira
	 */
	public class FileParser extends EventDispatcher {
		
		private var loader:URLLoader;
		private var subtitleType:String;
		
		
		public function FileParser() {
			this.loader = new URLLoader ();
			this.loader.addEventListener (Event.COMPLETE, onLoadSubtitle);
		}
		public function parse (urlSubtitle:String, type:String = "srt"):void {
			this.subtitleType = type;
			this.loader.load (new URLRequest (urlSubtitle));
		}
		
		private function onLoadSubtitle(e:Event):void {
			switch (this.subtitleType) {
				case SubtitleType.SRT: this.parseSRT (); break;
				case SubtitleType.SUB: this.parseSUB (); break;
				case SubtitleType.SSA: this.parseSSA (); break;
			}
		}
		
		/**
		 * Parse loaded data to SRT format.
		 */
		private function parseSRT():void {
			var blocks:Vector.<SubtitleBlock> = new Vector.<SubtitleBlock>();
			
			var subtitles:Array = this.loader.data.split (/\n\r?\n/);
			
			for (var i:int = 0; i < subtitles.length - 1; i++) {
				var blockData:String = String (subtitles[i]);
				var blockParts:Array = blockData.split (/\n\r?/);
				var times:Array = String(blockParts[1]).split (/ ?--> ?/);
				var block:SubtitleBlock = new SubtitleBlock ();
				block.id = int (blockParts[0]);				
				block.startTime = new SubtitleTime (times[0]);
				block.endTime = new SubtitleTime (times[1]);
				for (var j:int = 2; j < blockParts.length ; j++) {
					block.text += blockParts[j];
				}
				blocks.push (block);
			}		
			
			var evento:FileParserEvent = new FileParserEvent (FileParserEvent.PARSE_COMPLETE, blocks);
			this.dispatchEvent (evento);
		}
		
		private function parseSSA():void {
			// TODO Implement the SSA parser
		}
		
		private function parseSUB():void {
			// TODO Implement the SUB parser
		}
		
		
	}

}